package com.threadmethod.CAS;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;

import java.time.temporal.ValueRange;

/**
 * @PackageName:com.threadmethod.CAS
 * @ClassName:Test01
 * @Description: 使用CAS实现一个线程安全的计数器
 * @Author: zhangxiaoyu
 * @date 2020/12/10 16:41
 */
public class Test01 {

    public static void main(String[] args){
         CASCounter casCounter = new CASCounter();
         for(int i = 0;i<10;i++){
             new Thread(new Runnable() {
                 @Override
                 public void run() {
                     System.out.println(casCounter.incrementAndGet());
                 }
             }).start();
         }
    }

}
class CASCounter{
    //修饰变量 使线程可见
    volatile private long value;

    public long getValue(){
        return value;
    }

    //定义同一个方法
    private boolean compareAndSwap(long expectVale,long newValue){
        //如果当前value值与期望的值一样，就把当前的value一样，就把当前的值替换
        synchronized (this){
            if(value==expectVale){
                value = newValue;
                return true;
            }else {
                return false;
            }

        }

    }
    //定义一个计数器
    public long incrementAndGet(){
        long oldValue;
        long newValue;

        do{
            oldValue = value;
            newValue = oldValue+1;
        }while (!compareAndSwap(oldValue,newValue));

        return newValue;
    }

}